<script setup lang="ts">
import {nextTick, onMounted, ref, defineEmits, reactive} from 'vue'
import SysDialog from '@/components/dialog/SysDialog.vue'
import useDialog from '@/hooks/useDialog'
import {getQuoteStructApi, updateQuoteStructApi} from '@/api/quote'
import {QuoteProductUpdateDto} from '@/api/quote/type'
import {ElMessage} from 'element-plus'

const {dialog, onShow, onClose} = useDialog()

const getQuoteStructParam = reactive({
  quoteId: '',
  code: '',
})

// 树形数据
const treeData = ref<any[]>([])
const loading = ref(false)

// 加载结构数据
const loadStructure = async (quote: string, code: string) => {
  loading.value = true
  try {
    const res = await getQuoteStructApi(quote, code)
    if (res?.data) {
      treeData.value = [res.data]
    }
  } catch (error) {
    console.error('获取结构失败:', error)
    ElMessage.error('获取结构失败')
  } finally {
    loading.value = false
  }
}

// 显示弹窗
const show = (quote: string, code: string) => {
  dialog.title = '产品结构'
  dialog.width = 1000
  dialog.height = 500
  loadStructure(quote, code)
  getQuoteStructParam.quoteId = quote
  getQuoteStructParam.code = code
  onShow()
}

// 定义暴露的方法
defineExpose({
  show,
  onClose,
})

const handleUpdatePrice = async (row: any) => {
  console.log("更新行" + treeData.value[0]?.quantity)
  try {
    const params: QuoteProductUpdateDto = {
      id: row.id,
      purchasePrice: row.purchasePrice?.toString(),
      quantity: treeData.value[0]?.quantity
    }
    await updateQuoteStructApi(params)
    ElMessage.success('修改价格成功')
    loadStructure(getQuoteStructParam.quoteId, getQuoteStructParam.code)
  } catch (error) {
    console.error('修改价格失败:', error)
    ElMessage.error('修改价格失败')
  }
}

// 定义emit事件
const emit = defineEmits(["confirmQuoteProductUpdate"])

const confirmBom = () => {
  emit('confirmQuoteProductUpdate', treeData.value[0])
}
</script>

<template>
  <sys-dialog :title="dialog.title"
              :width="dialog.width"
              :visible="dialog.visible"
              :height="dialog.height"
              @onClose="onClose"
              @on-confirm="confirmBom">
    <template #content>
      <div class="structure-container"
           v-loading="loading">
        <el-table :data="treeData"
                  border
                  row-key="id"
                  default-expand-all
                  :tree-props="{
              children: 'children',
              hasChildren: 'hasChildren'
            }">
          <el-table-column prop="bomCode"
                           label="BOM编码"
                           min-width="120" />
          <el-table-column prop="bomName"
                           label="BOM名称"
                           min-width="150" />
          <el-table-column prop="quantity"
                           label="数量"
                           min-width="80"
                           align="right">
            <template #default="scope">
              <el-tag size="small"
                      type="info"
                      v-if="scope.row.quantity">
                {{ scope.row.quantity }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="purchasePrice"
                           label="单价"
                           min-width="100"
                           align="right">
            <template #default="scope">
              <el-input-number v-model="scope.row.purchasePrice"
                               :min="0"
                               :precision="2"
                               size="small"
                               style="width: 120px"
                               @change="handleUpdatePrice(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column prop="totalPrices"
                           label="总价"
                           min-width="100"
                           align="right">
            <template #default="scope">
              <el-tag size="small"
                      type="danger">
                ¥{{ scope.row.totalPrices }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </template>
  </sys-dialog>
</template>

<style scoped lang="scss">
.structure-container {
  padding: 10px;
  height: 100%;
  overflow: auto;

  :deep(.el-table) {
    // 树形缩进
    .el-table__indent {
      padding-left: 20px;
    }

    // 展开图标
    .el-table__expand-icon {
      height: 28px;
      line-height: 28px;
    }

    // 单元格内容垂直居中
    .el-table__cell {
      vertical-align: middle;
    }
  }

  :deep(.el-tag) {
    margin: 0 2px;
  }

  :deep(.el-tag--small) {
    height: 22px;
    padding: 0 8px;
    font-size: 12px;
  }
}
</style>
